<template>
  <div>
    <!-- -->
    <h3>员工管理</h3>
<!--    <el-button type="primary" @click="select">查询属性</el-button>-->
    <div class="search">
      员工姓名
      <el-input
          v-model="queryParam.name"
          style="width: 240px"
          placeholder="请输入员工姓名"
          clearable
      />
      <el-button type="primary" @click="handleSearchAllUser">搜索</el-button>
    </div>
    <div class="add">
      <el-button type="primary" @click="handleAddUser">添加员工</el-button>
    </div>
    <el-table :data="dataList" border style="width: 100%">
      <el-table-column prop="name" label="员工姓名" width="196" />
      <el-table-column prop="username" label="账号" width="220" />
      <el-table-column prop="phone" label="手机号" width="200" />
      <el-table-column prop="status" label="帐号状态" width="180" />
      <el-table-column prop="updateTime" label="最后操作时间" width="180" />
      <el-table-column label="操作" align="right" width="230">

        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="warning" @click="handleChangeStatus(scope.$index, scope.row)">
            禁用
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 当点击删除时显示提示框 -->
    <el-dialog
        v-model="dialogVisible"
        title="删除员工"
        width="500"
    >
<!--      :before-close="handleClose"-->
      <span>你确定要删除id为{{targetData.username}}员工吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlerConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>






    <div class="pagination_sign">
      <el-pagination background layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     v-model:current-page="curPage"
                     v-model:page-size="queryParam.size"
                     :total="total" />
    </div>


  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import { useRouter } from 'vue-router';

import {ElMessage, ElMessageBox} from 'element-plus'

const router = useRouter()



let dataList = ref([])

let total = ref(0)

let curPage = ref(1)



let mockUserData = ref([
  {
    "id":1,
    "name":"张三",
    "username":"zhangsan",
    "password":"113135c1sa3c1sad3dc1",
    "idNumber":"1513165165411",
    "phone":"13211664091",
    "sex":"男",
    "status":1,
    "createTime":"2024-9-4 23:02",
    "updateTime":"2024-9-4 23:02",
    "createUser":"1",
    "updateUser":"1"
  },
])
// 查询操作
// 查询所有员工
let handleSearchAllUser = async () => {
  const res = await getUserData(queryParam)
  // dataList.value = res.data.records
}


let select = () => {
  console.log(curPage.value);
}

/**
 * 页面挂载时获取数据
 */

const queryParam = reactive({
  name:'',
  page:1,
  size:9,
})


const getUserData = async () => {
  // console.log(res.data);
  const res = await employeePageQuery(queryParam)
  console.log(res)
  total.value = res.data.total
  // 赋值
  dataList.value = res.data.records
  dataList.value.forEach(element => {
    element.status = element.status === 1 ? "启用" : "禁用";
  });
}
onMounted( async ()=>{
  // console.log(data.value.name);
//  const res = await axios.get("/users.json")
  await getUserData()
//  console.log(dataList.value.length);
//  total.value = dataList.value.length
})


const handleCurrentChange = async (val) => {

  console.log(`current page: ${val}`)
  queryParam.page = val
  await getUserData()
}








/* 添加员工*/
const handleAddUser = () => {
  /**
   * 接口：/admin/employee/insert  请求体：
   */
  // 跳转到添加员工页面
  router.push("/admin/addEmployee")
}




/**
 * 编辑操作
 * @param {*} index
 * @param {*} row
 */
const handleEdit = (index, row) => {
  router.push({
    name:"updateEmployee",
    params:{
      id:row.id
    }
  })
  // console.log(index, row)
}






/**
 * 删除操作
 * @param {*} index
 * @param {*} row
 */
let targetData = ref()
const dialogVisible = ref(false)
// 关闭提示框时
const handleClose = () => {
  ElMessageBox.confirm('你确定要关闭吗')
      .then(() => {
        console.log("好的");
      })
      .catch(() => {
        // catch error
        console.log(222);
      })
}


/* 确认删除 */
const handlerConfirm = async () =>{
  // targetData 是本条记录
  console.log(targetData.value);
  try {
    // 取出id
    const { id } = targetData.value
    console.log(id);
    // 根据id删除
    const res = await deleteById(id)
    // 关闭弹出框
    dialogVisible.value = false
    console.log("删除成功");
    ElMessage.success("删除成功")
    // 获取数据
    await handleSearchAllUser()
  }catch (e) {
    ElMessage.error("删除失败："+e.message)
  }
  /**
   * 路径：/admin/employee/{id}
   * return {code,message}
   */
  // const res = await axios.delete("/admin/employee")




  /* 没后端 */


}

const handleDelete = (row) => {
  targetData.value = row
  //删除之前，提示
  dialogVisible.value = true
  // console.log(index, row)
}




/**
 * 启用禁用账号
 * @param {*} index 当前行的索引
 * @param {*} row 当前行的数据
 */
import { ElNotification } from 'element-plus'
import {deleteById, employeePageQuery, startOrStop} from "@/api/admin-api.js";
const handleChangeStatus = async (index, row) => {
  /* 以下是有后端写法 */
  try {
    console.log(index, row)
    const status = row.status === '启用'? 0:1
    const res = await startOrStop(status,row.id)
    ElMessage.success("账号:"+row.id+"已经禁用")
    row.status = status === 1?'启用':'禁用'
  }catch (e) {
    ElMessage.error("禁用失败："+e.message)
  }

  /* 以下是无后端写法 */

  // 根据id更改帐号状态，1为启用，0为
  // const id = row.id
  // console.log(id);
  // const crrentStatus = row.status
  // let setStatus = 0
  // if(crrentStatus === "禁用"){
  //   setStatus = '启用'
  // }else{
  //   setStatus = '禁用'
  // }


  // row.status = setStatus;
  // mockUserData.value[(row.id-1)%10].status = setStatus
  ElNotification({
    title: 'Success',
    message: '用户状态修改成功',
    type: 'success',
  })


}




</script>
<style lang="scss" scoped>
.search,{
  box-sizing: border-box;
  padding: 10px 0;
}
.add{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  margin-bottom: 10px;
}
.pagination_sign{
  width: 100%;
  position: absolute;
  top: 560px;
  display: flex;
  justify-content: center;
}
</style>
